package com.zoe.onelink.dubbo.mvc;

import com.fasterxml.classmate.TypeResolver;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.service.contexts.OperationContext;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Aspect
public class SwaggerExpandAspect {

    @Around("execution(* springfox.documentation.spring.web.readers.operation.OperationParameterReader.apply(..))")
    public Object pointCut(ProceedingJoinPoint point) throws Throwable {

        Object[] args = point.getArgs();
        OperationContext context = (OperationContext) args[0];

        if (context.requestMappingPattern().startsWith("/dubbo")) {
            log.debug("解析接口类:{} 接口:{}", context.getGroupName(), context.requestMappingPattern());
            context.operationBuilder().parameters(context.getGlobalOperationParameters());
            context.operationBuilder().parameters(readParameters(context));
            return null;
        } else {
            return point.proceed();
        }

    }

    private List<Parameter> readParameters(final OperationContext context) {

        List<Parameter> parameters = new ArrayList();
        parameters.add(new ParameterBuilder()
                .description("dubbo请求参数")
                .type(new TypeResolver().resolve(String.class))
                .name("postRequest")
                .parameterType("body")
                .required(true)
                .modelRef(new ModelRef("String"))
                .build());

        return parameters.stream().filter(item -> !item.isHidden()).collect(Collectors.toList());
    }

}